package com.ulic.customerManApplication.membermodule.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.stereotype.Service;

import com.ulic.customerManApplication.exception.SystemException;
import com.ulic.customerManApplication.membermodule.bo.Member;
import com.ulic.customerManApplication.membermodule.bo.SubMember;
import com.ulic.customerManApplication.membermodule.dao.MemberExtDao;
import com.ulic.customerManApplication.membermodule.dao.SubMemberDao;
import com.ulic.customerManApplication.membermodule.service.MemberExtService;
import com.ulic.customerManApplication.membermodule.vo.SubMemberVO;
import com.ulic.customerManApplication.pager.PagerModel;

@Service("memberExtService")
public class MemberExtServiceImpl implements MemberExtService {
	
	private final int MAX_CHILD = 5;

	private MemberExtDao memberExtDao;
	private SubMemberDao subMemberDao;
	
	
	public SubMemberDao getSubMemberDao() {
		return subMemberDao;
	}
	@Resource
	public void setSubMemberDao(SubMemberDao subMemberDao) {
		this.subMemberDao = subMemberDao;
	}

	public MemberExtDao getMemberExtDao() {
		return memberExtDao;
	}

	@Resource
	public void setMemberExtDao(MemberExtDao memberExtDao) {
		this.memberExtDao = memberExtDao;
	}

	@Override
	public Map<String , List<Member>> getMembersByPhone(Collection<String> phones) {
		Map<String , List<Member>> retVal = new HashMap<String , List<Member>>(); 
		if(phones != null && phones.size() > 0){
			List<Member> members = memberExtDao.getMembersByPhone(phones);
			if(members != null){
				for(Member m : members){
					List<Member> values = retVal.get(m.getCellPhone());
					if(values == null){
						values = new ArrayList<Member>();
						retVal.put(m.getCellPhone(), values);
					}
					values.add(m);
				}
			}
		}
		return retVal;
	}

	@Override
	public Map<String , List<Member>>  getMembersByIdCard(Collection<String> idCards) {
		Map<String , List<Member>> retVal = new HashMap<String , List<Member>>(); 
		if(idCards != null && idCards.size() > 0){
			List<Member> members =  memberExtDao.getMembersByIdCard(idCards);
			if(members != null){
				for(Member m : members){
					List<Member> values = retVal.get(m.getIdCard());
					if(values == null){
						values = new ArrayList<Member>();
						retVal.put(m.getIdCard(), values);
					}
					values.add(m);
				}
			}
		}
		return retVal;
	}

	@Override
	public Map<String, List<Member>> getMembersByName(Collection<String> names) {
		Map<String , List<Member>> retVal = new HashMap<String , List<Member>>(); 
		if(names != null && names.size() > 0){
			List<Member> members =  memberExtDao.getMembersByName(names);
			if(members != null){
				for(Member m : members){
					List<Member> values = retVal.get(m.getMemberName());
					if(values == null){
						values = new ArrayList<Member>();
						retVal.put(m.getMemberName(), values);
					}
					values.add(m);
				}
			}
		}
		return retVal;
	}

	@Override
	public Map<Integer, Member> getMembersById(Collection<Integer> ids) {
		Map<Integer , Member> retVal = new HashMap<Integer ,Member>(); 
		if(ids != null && ids.size() > 0){
			List<Member> members =  memberExtDao.getMembersById(ids);
			if(members != null){
				for(Member m : members){
					retVal.put(m.getId(), m);
				}
			}
		}
		return retVal;
	}

	@Override
	public void saveOrUpdateMembers(Collection<Member> members) {
		if(members != null && members.size() > 0){
			memberExtDao.saveOrUpdateMembers(members);
		}
	}

	@Override
	public void saveSubMembers(Collection<SubMember> subMembers) throws SystemException {
		if(subMembers != null && subMembers.size() > 0){
			//没有上级的会员
			List<SubMember> noParentSubMemberList = new ArrayList<SubMember>();
			//有上级的会员
			List<SubMember> childrenSubMemberList = new ArrayList<SubMember>();
			//出来parentMember
			for(SubMember s : subMembers){
				if(s.getParentMember() == null){
					noParentSubMemberList.add(s);
				}else{
					childrenSubMemberList.add(s);
				}
			}
			//先保存没有上级会员
			memberExtDao.saveSubMembers(noParentSubMemberList);
			//映射上级会员
			Map<String , Integer> parentPhoneIdMap = new HashMap<String , Integer>();
			//用于记录该手机号对应孩子的个数
			Map<String , Integer> childNumMap = new HashMap<String , Integer>();
			for(SubMember s : noParentSubMemberList){
				parentPhoneIdMap.put(s.getSub_cellPhone(), s.getSub_id());
			}
			for(SubMember s : childrenSubMemberList){
				String cellPhone = s.getParentMember().getSub_cellPhone();
				if(StringUtils.isBlank(cellPhone)){
					throw new SystemException("会员（" + s.getSub_memberName() + "）附属手机号码不能为空！");
				}else{
					Integer parentId = parentPhoneIdMap.get(cellPhone);
					if(parentId == null){
						throw new SystemException("附属手机号码（" + cellPhone + "）找不到对应的附属会员！");
					}else{
						s.getParentMember().setSub_id(parentId);
					}
				}
				
				Integer num = childNumMap.get(cellPhone);
				if(num == null){
					num = 0;
				}else if(num > MAX_CHILD){
					throw new SystemException("该手机号（" + cellPhone + "）对应的子会员不能超过" + MAX_CHILD + "个" );
				}
				childNumMap.put(cellPhone, ++num);
			}
			
			//保存下级会员
			memberExtDao.saveSubMembers(childrenSubMemberList);
			
			
		}
	}

	@Override
	public List<SubMember> getSubMembersByMember(Integer id) {
		List<SubMember> retVal = new ArrayList<SubMember>();
		List<SubMember> list =  memberExtDao.getSubMembersByMember(id);
		if(list != null){
			retVal.addAll(list);
		}
		return retVal;
		
	}
	@Override
	public PagerModel getSubMembers(SubMemberVO subMemberVO, int curPage) {
		if(StringUtils.isBlank(subMemberVO.getMemberEnjoyId())){
			return subMemberDao.getSubMembers(subMemberVO, curPage);
		}else{
			return memberExtDao.getMemberEnjoySubMembers(subMemberVO , curPage);
		}
	}
	@Override
	public SubMember getMemberEnjoySubMemberByPhone(String sub_cellPhone,
			String memberEnjoyId) {
		return memberExtDao.getMemberEnjoySubMemberByPhone(sub_cellPhone , memberEnjoyId);
	} 
	
	@Override
	public void updateDatabaseForMember() throws SystemException {
		List<SubMember> subMemberList = memberExtDao.getNoMemberSubMember(); 
		List<Member> memberList = memberExtDao.getAllMember();
		Map<String , List<Member>> memberNameMap = new HashMap<String  ,  List<Member>>();
		for(Member member : memberList){
			String name = member.getMemberName();
			List<Member> list = memberNameMap.get(name);
			if(list == null){
				list = new ArrayList<Member>();
				memberNameMap.put(name, list);
			}
			list.add(member);
		}
		
		List<SubMember> wantUpdateSubMember = new ArrayList<SubMember>();
		for(SubMember subMember : subMemberList){
			String name = subMember.getSub_memberName();
			List<Member> list = memberNameMap.get(name);
			if(list != null){
				//优先级1111 高优先级在低位
				int[] prioritys = new int[list.size()];
				for(int i = 0 ; i < list.size() ; i++){
					Member m = list.get(i);
					//机构优先级最高
					if(equalsO(subMember.getSubCity() , m.getSubCity()) && equalsO(subMember.getSubCompany() , m.getSubCompany())){
						prioritys[i] += 1;
					}
					//idcard优先级
					if(equalsO(subMember.getSub_idCard(), m.getIdCard())){
						prioritys[i] += 2;
					}
					//电话号码
					if(equalsO(subMember.getSub_cellPhone(),m.getCellPhone())){
						prioritys[i] += 4;
					}
					//email
					if(equalsO(subMember.getSub_email(), m.getEmail())){
						prioritys[i] += 8;
					}
				}
				int[] stepNums = new int[list.size()];
				for(int i = 0 ; i < list.size() ; i++){
					while((prioritys[i] & 1) == 1){
						stepNums[i]++;
						prioritys[i]>>=1;
					}
				}
				int maxIndex = -1;
				int maxStep = 0;
				for(int i = 0 ; i < list.size() ;i++){
					if(stepNums[i] > maxStep){
						maxStep = stepNums[i];
						maxIndex = i;
					}
				}
				if(maxIndex > -1){
					subMember.setMember(list.get(maxIndex));
					wantUpdateSubMember.add(subMember);
				}
			}
		}
		memberExtDao.saveOrUpdateSubMember(wantUpdateSubMember);
	}
	
	private boolean equalsO(Object o1 , Object o2){
		if(o1 == null){
			if(o2 == null){
				return true;
			}else{
				return false;
			}
		}else{
			return o1.equals(o2);
		}
	}

}
